package org.itboys.ace.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.dto.UserRewardDTO;
import org.itboys.admin.entity.AdminUser;
import org.itboys.admin.service.AdminUserService;
import org.itboys.admin.tools.AdminCookieHolder;
import org.itboys.admin.tools.LoginHolder;
import org.itboys.admin.tools.WebConstants;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.seller.constant.CaliforniaSiteConstant;
import org.itboys.seller.dto.MatchRecordVO;
import org.itboys.seller.dto.ScoreSourceVO;
import org.itboys.seller.dto.SiteUserVO;
import org.itboys.seller.entity.*;
import org.itboys.seller.meta.Account;
import org.itboys.seller.meta.MatchInfo;
import org.itboys.seller.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hzliangchong1@corp.netease.com
 *         Date 2016/10/22.
 */
@RestController
@RequestMapping("/site")
public class SiteController extends BaseController {

    @Autowired
    private CaliforniaSiteUserService californiaSiteUserService;

    @Autowired
    private RankingUserService rankingUserService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private SiteUserEditService siteUserEditService;

    @Autowired
    private ChangeScoreRecordService changeScoreRecordService;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private RewardRecordService rewardRecordService;
    @Resource
    private GetRewardRecordService getRewardRecordService;

    /**
     * 进入注册页面
     */
    @RequestMapping("/reg")
    public ModelAndView login(Model model,HttpServletRequest request){
        return new ModelAndView("site/reg");

    }

    /**
     * 进入基本信息页
     */
    @RequestMapping("/toBaseInfoVM")
    public ModelAndView toBaseInfoVM(Model model,HttpServletRequest request) {
        long siteUserId= Long.valueOf(AdminCookieHolder.getAdminUserId());
        SiteUser siteUser = californiaSiteUserService.getAdminUserByUserId(siteUserId);
        model.addAttribute("userInfo", siteUser);
        return new ModelAndView("site/userBaseInfo");
    }

    /**
     * 更新信息
     */
    @RequestMapping("/editSiteUser")
    public void editSiteUser(@ModelAttribute SiteUserEdit user,
                           HttpServletRequest request,HttpServletResponse response) {

        SiteUser proUser = californiaSiteUserService.getAdminUserByUserId(user.getUserId());
        if (proUser == null) {
            AjaxUtils.renderText(response, "用户不存在或已被冻结");
            return;
        }
        SiteUser phoneUser = californiaSiteUserService.getAdminUserByPhone(user.getPhone());
        if (phoneUser != null && phoneUser.getUserId() != user.getUserId()) {
            AjaxUtils.renderText(response, CommonConstants.EXISTED);
            return;
        }
        if (user.getRecUserId() != 0) {
            proUser = californiaSiteUserService.getAdminUserByUserId(user.getRecUserId());
            if (proUser == null) {
                AjaxUtils.renderText(response, "推荐人不存在");
                return;
            }
        }
        user.setType(1);
        siteUserEditService.insert(user);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);
    }

    /**
     * 进入修改密码页
     */
    @RequestMapping("/toPassWordXg")
    public ModelAndView toPassWordXg(Model model,HttpServletRequest request) {
        return new ModelAndView("site/password-xg");
    }

    /**
     * 更新信息
     */
    @RequestMapping("/updateSiteUserPassword")
    public void updateSiteUserPassword(String oldPassword, String password,
                           HttpServletRequest request,HttpServletResponse response) {
        long siteUserId= Long.valueOf(AdminCookieHolder.getAdminUserId());
        SiteUser proUser = californiaSiteUserService.getAdminUserByUserId(siteUserId);
        if (proUser == null) {
            AjaxUtils.renderText(response, "用户不存在或已被冻结");
            return;
        }
        if(!StringUtils.equals(proUser.getPassword(), Digests.md5(oldPassword))){
            AjaxUtils.renderText(response, "-1");//密码不正确
            return ;
        }
        proUser.setPassword(Digests.md5(password));
        californiaSiteUserService.update(proUser);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);

    }

    @RequestMapping("/rankingList")
    public void rankingList(Integer type,
                            HttpServletRequest request, HttpServletResponse response) {
        if (type == null) {
            type = 0;
        }
        long siteUserId= Long.valueOf(AdminCookieHolder.getAdminUserId());
        SiteUser siteUser = californiaSiteUserService.getAdminUserByUserId(siteUserId);
        RankingUserDB rankingUserDB = rankingUserService.getLatestRankingUserBySellerUserName(0, siteUser.getSellerUserName());
        if (rankingUserDB == null) {
            return;
        }
        List<SiteUser> siteUserList;
        if (type == 0) {
            siteUserList = californiaSiteUserService.getAdminUserByUserIds(rankingUserDB.getUserIds());
        } else if (type == 1) {
            siteUserList = californiaSiteUserService.getAdminUserByUserIds(rankingUserDB.getsUserIds());
        } else {
            siteUserList = californiaSiteUserService.getAdminUserByUserIds(rankingUserDB.getSsUserIds());
        }
        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<Long> userIds = siteUserList.stream().map(SiteUser::getUserId).collect(Collectors.toList());
        List<Long> recUserIds = siteUserList.stream().map(SiteUser::getRecUserId).distinct().collect(Collectors.toList());
        List<SiteUser> recSiteUsers = californiaSiteUserService.getAdminUserByUserIds(recUserIds);
        Map<Long, SiteUser> recSiteUserMap = recSiteUsers.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<Account> accounts = accountService.batchQueryAccount(userIds);
        Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

        Map<Long, Integer> actualScores;
        Map<Long, Integer> totalScores;
        List<Long> userIdList;
        if (type == 0) {
            actualScores = rankingUserDB.getActualScores();
            totalScores = rankingUserDB.getTotalScores();
            userIdList = rankingUserDB.getUserIds();
        } else if (type == 1) {
            actualScores = rankingUserDB.getsActualScores();
            totalScores = rankingUserDB.getsTotalScores();
            userIdList = rankingUserDB.getsUserIds();
        } else {
            actualScores = rankingUserDB.getSsActualScores();
            totalScores = rankingUserDB.getSsTotalScores();
            userIdList = rankingUserDB.getSsUserIds();
        }

        List<SiteUserVO> voList = userIdList.stream().map(userId -> {
            SiteUserVO vo = new SiteUserVO();
            SiteUser p = siteUserMap.get(userId);
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
            }
            SiteUser recSiteUser = recSiteUserMap.get(p.getRecUserId());
            if (recSiteUser != null) {
                vo.setRecMemberName(recSiteUser.getRealName());
            }

            Integer actualScore = actualScores.get(p.getUserId());
            Integer totalScore = totalScores.get(p.getUserId());
            vo.setActualScore(actualScore != null ? actualScore : 0);
            vo.setTotalScore(totalScore != null ? totalScore : 0);
            vo.setUpdateTime(p.getCt());
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }

    /**
     * 进入会员充值页面
     */
    @RequestMapping("/toRankingList")
    public ModelAndView toRankingList(Model model,HttpServletRequest request){
        AdminUser adminUser = adminUserService.getAdminUser("admin");
        if (adminUser != null) {
            model.addAttribute("lastTotalAmount", adminUser.getLastTotalAmount());
            model.addAttribute("totalAmount",adminUser.getTotalAmount());
            model.addAttribute("recentTotalAmount",adminUser.getRecentTotalAmount());
            model.addAttribute("rewardBalance",adminUser.getRewardBalance());
            model.addAttribute("totalReward",adminUser.getRewardBalance() + adminUser.getRecentTotalAmount());
            model.addAttribute("accountId",adminUser.getUsername());
        }
        return new ModelAndView("site/ranking-list");

    }

    /**
     * 进入会员充值页面
     */
    @RequestMapping("/toSRankingList")
    public ModelAndView toSRankingList(Model model,HttpServletRequest request){
        AdminUser adminUser = adminUserService.getAdminUser("admin");
        if (adminUser != null) {
            model.addAttribute("lastTotalAmount", adminUser.getLastTotalAmount());
            model.addAttribute("totalAmount",adminUser.getTotalAmount());
            model.addAttribute("recentTotalAmount",adminUser.getRecentTotalAmount());
            model.addAttribute("rewardBalance",adminUser.getRewardBalanceS());
            model.addAttribute("totalReward",adminUser.getRewardBalanceS() + adminUser.getRecentTotalAmount());
            model.addAttribute("accountId",adminUser.getUsername());
        }
        return new ModelAndView("site/ranking-s-list");

    }

    /**
     * 进入会员充值页面
     */
    @RequestMapping("/toSSRankingList")
    public ModelAndView toSSRankingList(Model model,HttpServletRequest request){
        AdminUser adminUser = adminUserService.getAdminUser("admin");
        if (adminUser != null) {
            model.addAttribute("lastTotalAmount", adminUser.getLastTotalAmount());
            model.addAttribute("totalAmount",adminUser.getTotalAmount());
            model.addAttribute("recentTotalAmount",adminUser.getRecentTotalAmount());
            model.addAttribute("rewardBalance",adminUser.getRewardBalanceSS());
            model.addAttribute("totalReward",adminUser.getRewardBalanceSS() + adminUser.getRecentTotalAmount());
            model.addAttribute("accountId",adminUser.getUsername());
        }
        return new ModelAndView("site/ranking-ss-list");

    }

    @RequestMapping("/recentRankingList")
    public void recentRankingList(HttpServletRequest request, HttpServletResponse response) {
        List<Account> accounts = accountService.getRankingUsers();
        List<Long> userIds = accounts.stream().map(Account::getUserId).collect(Collectors.toList());
        Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

        List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = userIds.stream().map(userId -> {
            SiteUserVO vo = new SiteUserVO();
            SiteUser p = siteUserMap.get(userId);
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
                vo.setActualScore(account.getRecentScore());
                vo.setUpdateTime(account.getUpdateTime().getTime());
            }
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }

    @RequestMapping("/recentSRankingList")
    public void recentSRankingList(HttpServletRequest request, HttpServletResponse response) {
        List<Account> accounts = accountService.getSRankingUsers();
        List<Account> tmpAccountList = Lists.newArrayList();
        for (Account account : accounts) {
            if (getRewardRecordService.getByField("userId", account.getUserId()) == null) {
                tmpAccountList.add(account);
            }
        }
        List<Long> userIds = tmpAccountList.stream().map(Account::getUserId).collect(Collectors.toList());
        Map<Long, Account> accountMap = tmpAccountList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

        List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = userIds.stream().map(userId -> {
            SiteUserVO vo = new SiteUserVO();
            SiteUser p = siteUserMap.get(userId);
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
                vo.setActualScore(account.getRecentScoreS());
                vo.setUpdateTime(account.getUpdateTime().getTime());
            }
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }

    @RequestMapping("/recentSSRankingList")
    public void recentSSRankingList(HttpServletRequest request, HttpServletResponse response) {
        List<Account> accounts = accountService.getSSRankingUsers();
        List<Long> userIds = accounts.stream().map(Account::getUserId).collect(Collectors.toList());
        Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

        List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = userIds.stream().map(userId -> {
            SiteUserVO vo = new SiteUserVO();
            SiteUser p = siteUserMap.get(userId);
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
                vo.setActualScore(account.getRecentScoreSs());
                vo.setUpdateTime(account.getUpdateTime().getTime());
            }
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }

    /**
     * 进入上期获奖名单页面
     */
    @RequestMapping("/toRewardList")
    public ModelAndView toRewardList(Model model,HttpServletRequest request){
        return new ModelAndView("site/reward-list");

    }

    /**
     * 进入上期获奖名单页面
     */
    @RequestMapping("/toSRewardList")
    public ModelAndView toSRewardList(Model model,HttpServletRequest request){
        return new ModelAndView("site/reward-s-list");

    }

    /**
     * 进入上期获奖名单页面
     */
    @RequestMapping("/toSSRewardList")
    public ModelAndView toSSRewardList(Model model,HttpServletRequest request){
        return new ModelAndView("site/reward-ss-list");

    }

    /**
     * 进入上期获奖名单页面
     */
    @RequestMapping("/toScoreSourceList")
    public ModelAndView toScoreSourceList(Model model,HttpServletRequest request){
        RewardRecordDB recordDB = rewardRecordService.getLastedRecord(0);
        long ct = recordDB.getCt();
        long now = System.currentTimeMillis();
        int rewardType = 0;
        int rank = 0;
        long siteUserId= Long.valueOf(AdminCookieHolder.getAdminUserId());
        if (TimeUtils.isSameDay(new Date(ct + 3600 * 1000), new Date(now))) {
            List<Long> userIds = recordDB.getUserIds();
            if (userIds.contains(siteUserId)) {
                rewardType = 1;
                rank = userIds.indexOf(siteUserId) + 1;
                List<ChangeScoreRecord>  records = changeScoreRecordService.getOfferScoreRecordsOneDay(siteUserId);
                Map<Long, Integer> id2ScoreMap = Maps.newHashMap();
                for (ChangeScoreRecord record : records) {
                    Integer sum = id2ScoreMap.get(record.getResourceUserId());
                    if (sum == null) {
                        id2ScoreMap.put(record.getResourceUserId(), record.getScoreDelta());
                    } else {
                        id2ScoreMap.put(record.getResourceUserId(), sum + record.getScoreDelta());
                    }
                }
                List<ScoreSourceVO> voList = Lists.newArrayList();
                ScoreSourceVO vo;
                for (Long userId : id2ScoreMap.keySet()) {
                    SiteUser user = californiaSiteUserService.getByField("userId", userId);
                    if (user != null) {
                        vo = new ScoreSourceVO();
                        if (StringUtils.isNotBlank(user.getPhone())) {
                            vo.setPhone(user.getPhone().substring(user.getPhone().length() - 4));
                        }
                        vo.setScore(id2ScoreMap.get(userId));
                        vo.setRealName(user.getRealName());
                        voList.add(vo);
                    }
                }
                model.addAttribute("scoreList", voList);
            } else {
                SiteUser user = californiaSiteUserService.getByField("userId", siteUserId);
                if (user != null && user.getRecUserId() != 0 && userIds.contains(user.getRecUserId())) {
                    user = californiaSiteUserService.getByField("userId", user.getRecUserId());
                    if (user != null) {
                        rewardType = 2;
                        rank = userIds.indexOf(user.getUserId()) + 1;
                        model.addAttribute("recName", user.getRealName());
                        int sumScore = changeScoreRecordService.getOfferScoreOneDay(siteUserId, user.getUserId());
                        model.addAttribute("sumScore", sumScore);
                    }

                }
            }
        }
        model.addAttribute("rewardType", rewardType);
        model.addAttribute("rank", rank);
        return new ModelAndView("site/score-source-list");
    }

    /**
     * 进入上期获奖名单页面
     */
    @RequestMapping("/getRewardList")
    public void getRewardList(Model model, int type, HttpServletRequest request,
                              HttpServletResponse response){
        RewardRecordDB recordDB = rewardRecordService.getLastedRecord(0);
        List<UserRewardDTO> dtoList = Lists.newArrayList();
        if (recordDB != null && CollectionUtils.isNotEmpty(recordDB.getUserIds())) {
            List<SiteUser> userList = californiaSiteUserService.getAdminUserByUserIds(recordDB.getUserIds());
            Map<Long, SiteUser> id2UserMap = userList.stream()
                    .collect(Collectors.toMap(SiteUser::getUserId, p -> p));
            int order = 1;
            for (Long userId : recordDB.getUserIds()) {
                UserRewardDTO dto = new UserRewardDTO();
                SiteUser user = id2UserMap.get(userId);
                if (user == null) {
                    continue;
                }
                dto.setDate(TimeUtils.format(new Date(recordDB.getCt()), "yyyy-MM-dd HH:mm:ss"));
                dto.setIdCard(user.getIdCard());
                dto.setMemberName(user.getMemberName());
                dto.setRealName(user.getRealName());
                if (StringUtils.isNotBlank(user.getPhone()) && user.getPhone().length() > 5) {
                    dto.setPhone(user.getPhone().substring(user.getPhone().length() - 4));
                }
                dto.setOrder(order++);
                dtoList.add(dto);
            }
        }
        JsonPageUtils.renderJsonPage(Long.valueOf(dtoList.size()), dtoList, response);

    }

    /**
     * 分页查询充值记录
     *
     * @return
     */
    @RequestMapping("/scorelist")
    public void scorelist(HttpServletRequest request, HttpServletResponse response) {
        Page<ChangeScoreRecord> scorePage = changeScoreRecordService.pageQuery(request);

        List<Long> userIds = scorePage.getData().stream().map(ChangeScoreRecord::getUserId).collect(Collectors.toList());
        List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

        List<Long> resourceUserIds = scorePage.getData().stream().map(ChangeScoreRecord::getResourceUserId).collect(Collectors.toList());
        List<SiteUser> resourceSiteUserList = californiaSiteUserService.getAdminUserByUserIds(resourceUserIds);
        Map<Long, SiteUser> resourceSiteUserMap = resourceSiteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = scorePage.getData().stream().filter(p -> {
            SiteUser siteUser = siteUserMap.get(p.getUserId());
            return siteUser != null;
        }).map(p -> {
            SiteUserVO vo = new SiteUserVO();
            vo.setUserId(p.getUserId());
            vo.setId(p.getId());
            SiteUser siteUser = siteUserMap.get(p.getUserId());
            if (siteUser != null) {
                vo.setMemberName(siteUser.getMemberName());
                vo.setCompanyName(siteUser.getCompanyName());
                vo.setPhone(siteUser.getPhone());
                vo.setRecUserId(siteUser.getRecUserId());
                vo.setRealName(siteUser.getRealName());
                vo.setIdCard(siteUser.getIdCard());
            }
            vo.setScoreDelta(p.getScoreDelta());
            vo.setAuditState(p.getAuditState());
            vo.setAuditName(p.getAuditName());
            SiteUser resourceSiteUser = resourceSiteUserMap.get(p.getResourceUserId());
            if (resourceSiteUser != null) {
                vo.setResourceName(p.getUserId() == p.getResourceUserId() ? "本人" : resourceSiteUser.getRealName());
                vo.setResourcePhone(resourceSiteUser.getPhone());
            }
            vo.setUpdateTime(p.getUt());
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(scorePage.getTotal(),scorePage.getTotalPages(), voList, response);
    }
}
